public class PriorityQueue {
    public int[] elem;
    public int usedSize;

    public PriorityQueue() {
        elem = new int[10]; // Initial capacity of 10, you can modify it as needed
        usedSize = 0;
    }

    /**
     * 建堆的时间复杂度：
     *
     * @param array
     */
    public void createHeap(int[] array) {
        for (int i = 0; i < array.length; i++) {
            elem[i] = array[i];
            usedSize++;
        }

        for (int i = (usedSize - 1) / 2; i >= 0; i--) {
            shiftDown(i, usedSize);
        }
    }

    /**
     * @param root 是每棵子树的根节点的下标
     * @param len  是每棵子树调整结束的结束条件
     *             向下调整的时间复杂度：O(logn)
     */
    private void shiftDown(int root, int len) {
        int parent = root;
        int child = 2 * parent + 1;

        while (child < len) {
            if (child + 1 < len && elem[child] < elem[child + 1]) {
                child++;
            }

            if (elem[parent] < elem[child]) {
                int temp = elem[parent];
                elem[parent] = elem[child];
                elem[child] = temp;

                parent = child;
                child = 2 * parent + 1;
            } else {
                break;
            }
        }
    }


    /**
     * 入队：仍然要保持是大根堆
     *
     * @param val
     */
    public void push(int val) {
        if (isFull()) {
            // Resize the array if it is full
            int[] newArray = new int[elem.length * 2];
            System.arraycopy(elem, 0, newArray, 0, elem.length);
            elem = newArray;
        }

        elem[usedSize++] = val;
        shiftUp(usedSize - 1);
    }

    private void shiftUp(int child) {
        int parent = (child - 1) / 2;

        while (child > 0 && elem[parent] < elem[child]) {
            int temp = elem[parent];
            elem[parent] = elem[child];
            elem[child] = temp;

            child = parent;
            parent = (child - 1) / 2;
        }
    }

    public boolean isFull() {
        return usedSize == elem.length;
    }

    /**
     * 出队【删除】：每次删除的都是优先级高的元素
     * 仍然要保持是大根堆
     */
    public void pollHeap() {
        if (isEmpty()) {
            throw new IllegalStateException("Priority queue is empty");
        }

        elem[0] = elem[usedSize - 1];
        usedSize--;
        shiftDown(0, usedSize);
    }

    public boolean isEmpty() {
        return usedSize == 0;
    }

    /**
     * 获取堆顶元素
     *
     * @return
     */
    public int peekHeap() {
        if (isEmpty()) {
            throw new IllegalStateException("Priority queue is empty");
        }

        return elem[0];
    }
/*    public void heapSort(){
        int end = usedSize-1;
        while (end>0){
            swap(0,end);
            shiftDown(0,end);
            end--;
        }
    }*/

}
